<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}
require_once 'track_online.php';
// 函数：检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        file_put_contents($filename, $defaultContent);
    }

    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    if (!is_array($data)) {
        file_put_contents($filename, $defaultContent);
        $data = json_decode($defaultContent, true);
    }

    return $data;
}

// 加载群聊和用户数据
$groups = ensureFile('groups.json');
$users = ensureFile('users.json');
$currentUser = null;

// 获取当前用户
foreach ($users as &$user) {
    if ($user['username'] === $_SESSION['username']) {
        $currentUser = &$user;
        break;
    }
}

if (!$currentUser) {
    die("用户数据不存在，请重新登录。");
}

// 搜索群聊逻辑
$searchResults = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_group_id'])) {
    $searchGroupId = intval($_POST['search_group_id']);

    foreach ($groups as $group) {
        if ($group['id'] === $searchGroupId) {
            $searchResults[] = $group;
            break;
        }
    }
}

// 加入群聊逻辑直接处理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['join_group_id'])) {
    $joinGroupId = intval($_POST['join_group_id']);

    foreach ($groups as &$group) {
        if ($group['id'] === $joinGroupId) {
            if (!in_array($currentUser['username'], $group['members'])) {
                $group['members'][] = $currentUser['username'];
                file_put_contents('groups.json', json_encode($groups));
                $currentUser['groups'][] = $joinGroupId;
                file_put_contents('users.json', json_encode($users));
                $successMessage = "成功加入群聊：" . htmlspecialchars($group['name']);
            } else {
                $errorMessage = "您已加入该群聊，无需重复加入。";
            }
            break;
        }
    }

    if (!isset($successMessage) && !isset($errorMessage)) {
        $errorMessage = "加入群聊失败，群聊不存在或已解散。";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>加入群聊 - JIILCHAT</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="form-container">
        <h1>加入群聊</h1>
        <form method="POST">
            <label for="search_group_id">输入群聊号</label>
            <input type="text" id="search_group_id" name="search_group_id" required>
            <button type="submit">搜索</button>
        </form>
        <div class="search-results">
            <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_group_id'])): ?>
                <?php if (empty($searchResults)): ?>
                    <p class="error">未找到相关群聊。</p>
                <?php else: ?>
                    <ul>
                        <?php foreach ($searchResults as $result): ?>
                            <li>
                                群聊名：<?= htmlspecialchars($result['name']) ?>，
                                群号：<?= htmlspecialchars($result['id']) ?>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="join_group_id" value="<?= htmlspecialchars($result['id']) ?>">
                                    <button type="submit">加入</button>
                                </form>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            <?php endif; ?>

            <?php if (isset($successMessage)): ?>
                <p class="success"><?= htmlspecialchars($successMessage) ?></p>
            <?php elseif (isset($errorMessage)): ?>
                <p class="error"><?= htmlspecialchars($errorMessage) ?></p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>